package com.example.arithmeticleetcode.leetcode;

import java.util.HashSet;
import java.util.Set;

/**
 * @program: arithmetic-leetcode
 * @description:
 * @author: FangZhen
 * @create: 2020-06-23 11:38
 **/
public class Demo34 {

    public static void main(String[] args) {
        System.out.println(isPathCrossing("NE")); //false
        System.out.println(isPathCrossing("NESWW")); //true
        System.out.println(isPathCrossing("SN")); //true
    }

    public static boolean isPathCrossing(String path) {
        char[] chars = path.toCharArray();
        Set<String> pointSet = new HashSet<>();
        int x = 0;
        int y = 0;
        StringBuilder sb = new StringBuilder();
        pointSet.add(sb.append(x).append(y).toString());
        for (char aChar : chars) {
            sb.delete(0, Integer.MAX_VALUE);
            if ('N' == aChar) {
                y += 1;
            }
            if ('S' == aChar) {
                y -= 1;
            }
            if ('E' == aChar) {
                x += 1;
            }
            if ('W' == aChar) {
                x -= 1;
            }
            String s = sb.append(x).append(y).toString();
            if (pointSet.contains(s)) {
                return true;
            }
            pointSet.add(s);
        }
        return false;
    }
}
